package com.qdxht.dispenser.utils.image;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public abstract class SelectZipCallback extends SelectCallback {

    Context context;

    int fileSize = 0;

    List<File> fileList = new ArrayList<>();

    public SelectZipCallback(Context context){
        this.context = context;
    }

    @Override
    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
        fileSize = photos.size();
        for (Photo photo : photos) {
            compressImage(photo.path);
        }
    }

    @Override
    public void onCancel() {

    }

    public void compressImage(String imgPath){
        File file = new File(imgPath);
        Luban.with(context)
                .load(file)
                .ignoreBy(100)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        Log.d("lubanLog","new／"+"图片的大小为："+file.length()/1024+"KB");
                        fileList.add(file);
                        if(fileList.size() == fileSize){
                            success(fileList);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        onError(e);
                    }
                }).launch();
    }

    /**
     * Fired when a compression returns successfully, override to handle in your own code
     */
    public abstract void success(List<File> files);

    /**
     * Fired when a compression fails to complete, override to handle in your own code
     */
    public abstract void error(Throwable e);
}
